<template>
  <el-dialog
    v-model="visible"
    title="个人信息"
    width="600px"
    :close-on-click-modal="false"
    center
    class="profile-dialog"
  >
    <div class="profile-content">
      <!-- 用户头像区域 -->
      <div class="avatar-section">
        <div class="avatar-container" @click="editAvatar">
          <el-avatar :size="80" :src="userInfo.avatar" class="user-avatar">
            {{ userInfo.name ? userInfo.name.charAt(0) : 'U' }}
          </el-avatar>
          <div class="avatar-overlay">
            <el-icon><Camera /></el-icon>
          </div>
        </div>
        <p class="user-name">{{ userInfo.name || '用户' }}</p>
        <p class="user-role">{{ userInfo.role || '普通用户' }}</p>
      </div>

      <!-- 个人信息表单 -->
      <div class="form-section">
        <el-form
          ref="profileFormRef"
          :model="formData"
          :rules="formRules"
          label-width="80px"
          class="profile-form"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="用户名" prop="userName">
                <el-input v-model="formData.userName" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="昵称" prop="nickName">
                <el-input v-model="formData.nickName" placeholder="请输入昵称" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="手机号" prop="phonenumber">
                <el-input v-model="formData.phonenumber" placeholder="请输入手机号" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="formData.email" placeholder="请输入邮箱" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="性别">
                <el-radio-group v-model="formData.sex">
                  <el-radio value="0">男</el-radio>
                  <el-radio value="1">女</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="创建时间">
                <el-input v-model="formData.createTime" disabled />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="个人简介">
            <el-input
              v-model="formData.remark"
              type="textarea"
              :rows="3"
              placeholder="请输入个人简介"
              maxlength="200"
              show-word-limit
            />
          </el-form-item>
        </el-form>
      </div>

      <!-- 统计信息卡片 -->
<!--      <div class="stats-section">-->
<!--        <div class="stats-cards">-->
<!--          <div class="stats-card">-->
<!--            <div class="stats-icon">-->
<!--              <el-icon><Document /></el-icon>-->
<!--            </div>-->
<!--            <div class="stats-content">-->
<!--              <div class="stats-number">{{ userStats.novelsCount || 0 }}</div>-->
<!--              <div class="stats-label">我的小说</div>-->
<!--            </div>-->
<!--          </div>-->
<!--          <div class="stats-card">-->
<!--            <div class="stats-icon">-->
<!--              <el-icon><Edit /></el-icon>-->
<!--            </div>-->
<!--            <div class="stats-content">-->
<!--              <div class="stats-number">{{ userStats.wordsCount || 0 }}</div>-->
<!--              <div class="stats-label">总字数</div>-->
<!--            </div>-->
<!--          </div>-->
<!--          <div class="stats-card">-->
<!--            <div class="stats-icon">-->
<!--              <el-icon><View /></el-icon>-->
<!--            </div>-->
<!--            <div class="stats-content">-->
<!--              <div class="stats-number">{{ userStats.viewsCount || 0 }}</div>-->
<!--              <div class="stats-label">总阅读量</div>-->
<!--            </div>-->
<!--          </div>-->
<!--        </div>-->
<!--      </div>-->
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSave" :loading="saving">
          保存修改
        </el-button>
      </div>
    </template>

    <!-- 头像上传弹窗 -->
    <el-dialog
      v-model="avatarDialogVisible"
      title="修改头像"
      width="400px"
      center
      append-to-body
    >
      <div class="avatar-upload">
        <el-upload
          class="avatar-uploader"
          action="#"
          :show-file-list="false"
          :before-upload="beforeAvatarUpload"
          :http-request="uploadAvatar"
        >
          <img v-if="avatarUrl" :src="avatarUrl" class="avatar-preview" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
        <div class="upload-tips">
          <p>支持 JPG、PNG 格式</p>
          <p>文件大小不超过 2MB</p>
        </div>
      </div>
      <template #footer>
        <el-button @click="avatarDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmAvatar">确定</el-button>
      </template>
    </el-dialog>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, watch } from 'vue'
import useUserStore from '@/store/modules/user'
import { getUserProfile, updateUserProfile, uploadAvatar as uploadAvatarApi } from '@/api/system/user'
import { Camera, Document, Edit, View, Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:modelValue'])

const userStore = useUserStore()
const profileFormRef = ref()

// 弹窗显示状态
const visible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

// 用户信息
const userInfo = ref({
  name: '',
  nickName: '',
  avatar: '',
  role: '',
  createTime: ''
})

// 表单数据
const formData = reactive({
  userName: '',
  nickName: '',
  phonenumber: '',
  email: '',
  sex: '0',
  createTime: '',
  remark: ''
})

// 用户统计信息
const userStats = ref({
  novelsCount: 0,
  wordsCount: 0,
  viewsCount: 0
})

// 头像相关
const avatarDialogVisible = ref(false)
const avatarUrl = ref('')
const saving = ref(false)

// 表单验证规则
const formRules = {
  nickName: [
    { required: true, message: '请输入昵称', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  phonenumber: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ]
}

// 监听弹窗显示状态
watch(visible, (newVal) => {
  if (newVal) {
    loadUserProfile()
  }
})

// 加载用户信息
const loadUserProfile = async () => {
  try {
    const response = await getUserProfile()
    const user = response.data

    // 更新用户信息
    userInfo.value = {
      name: user.userName,
      nickName: user.nickName,
      avatar: user.avatar || userStore.avatar,
      role: response.roleGroup || '普通用户',
      createTime: user.createTime
    }

    // 更新表单数据
    Object.assign(formData, {
      userName: user.userName,
      nickName: user.nickName,
      phonenumber: user.phonenumber,
      email: user.email,
      sex: user.sex || '0',
      createTime: user.createTime,
      remark: user.remark || ''
    })

    // 模拟统计数据
    userStats.value = {
      novelsCount: Math.floor(Math.random() * 20) + 5,
      wordsCount: Math.floor(Math.random() * 100000) + 10000,
      viewsCount: Math.floor(Math.random() * 50000) + 5000
    }
  } catch (error) {
    console.error('加载用户信息失败:', error)
  }
}

// 编辑头像
const editAvatar = () => {
  avatarUrl.value = userInfo.value.avatar
  avatarDialogVisible.value = true
}

// 头像上传前验证
const beforeAvatarUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片格式文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 上传头像
const uploadAvatar = (file) => {
  const reader = new FileReader()
  reader.onload = (e) => {
    avatarUrl.value = e.target.result
  }
  reader.readAsDataURL(file.file)
}

// 确认头像
const confirmAvatar = async () => {
  if (!avatarUrl.value) return

  try {
    const formData = new FormData()
    const blob = await fetch(avatarUrl.value).then(r => r.blob())
    formData.append('avatarfile', blob, 'avatar.jpg')

    const response = await uploadAvatarApi(formData)
    userInfo.value.avatar = response.imgUrl
    userStore.avatar = response.imgUrl

    avatarDialogVisible.value = false
    ElMessage.success('头像更新成功')
  } catch (error) {
    console.error('头像上传失败:', error)
    ElMessage.error('头像上传失败')
  }
}

// 保存修改
const handleSave = async () => {
  if (!profileFormRef.value) return

  try {
    await profileFormRef.value.validate()
    saving.value = true

    await updateUserProfile(formData)

    // 更新用户store
    userStore.nickName = formData.nickName

    ElMessage.success('保存成功')
    visible.value = false
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败')
  } finally {
    saving.value = false
  }
}

// 取消
const handleCancel = () => {
  visible.value = false
}
</script>

<style lang="scss" scoped>
.profile-dialog {
  :deep(.el-dialog__body) {
    padding: 20px;
  }
}

.profile-content {
  .avatar-section {
    text-align: center;
    margin-bottom: 30px;
    padding-bottom: 20px;
    border-bottom: 1px solid #f0f0f0;

    .avatar-container {
      position: relative;
      display: inline-block;
      cursor: pointer;
      margin-bottom: 15px;

      .user-avatar {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        font-weight: bold;
        font-size: 32px;
        transition: transform 0.3s;

        &:hover {
          transform: scale(1.05);
        }
      }

      .avatar-overlay {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(0, 0, 0, 0.5);
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        opacity: 0;
        transition: opacity 0.3s;

        .el-icon {
          color: white;
          font-size: 20px;
        }
      }

      &:hover .avatar-overlay {
        opacity: 1;
      }
    }

    .user-name {
      font-size: 20px;
      font-weight: bold;
      color: #333;
      margin: 0 0 5px 0;
    }

    .user-role {
      font-size: 14px;
      color: #666;
      margin: 0;
    }
  }

  .form-section {
    margin-bottom: 30px;

    .profile-form {
      .el-form-item {
        margin-bottom: 20px;
      }
    }
  }

  .stats-section {
    .stats-cards {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      gap: 20px;

      .stats-card {
        background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
        color: white;
        padding: 20px;
        border-radius: 12px;
        display: flex;
        align-items: center;
        gap: 15px;
        transition: transform 0.3s;

        &:hover {
          transform: translateY(-2px);
        }

        .stats-icon {
          width: 50px;
          height: 50px;
          background: rgba(255, 255, 255, 0.2);
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;

          .el-icon {
            font-size: 24px;
          }
        }

        .stats-content {
          .stats-number {
            font-size: 24px;
            font-weight: bold;
            margin-bottom: 5px;
          }

          .stats-label {
            font-size: 14px;
            opacity: 0.9;
          }
        }
      }
    }
  }
}

.avatar-upload {
  text-align: center;

  .avatar-uploader {
    .avatar-preview {
      width: 120px;
      height: 120px;
      border-radius: 50%;
      object-fit: cover;
    }

    .avatar-uploader-icon {
      width: 120px;
      height: 120px;
      border: 2px dashed #d9d9d9;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 28px;
      color: #8c939d;
      cursor: pointer;
      transition: border-color 0.3s;

      &:hover {
        border-color: #409eff;
      }
    }
  }

  .upload-tips {
    margin-top: 15px;
    color: #666;
    font-size: 12px;

    p {
      margin: 5px 0;
    }
  }
}

.dialog-footer {
  text-align: right;
}
</style>
